#include <stdio.h>
#include <iostream>
#include </usr/local/include/modbus/modbus.h>
#include <unistd.h>
using namespace std;

int main(void) {
  modbus_t *mb;
  uint16_t tab_reg[32];

  mb = modbus_new_tcp("192.168.1.1", 502);
  cout<<modbus_connect(mb)<<endl;

  uint8_t  mydata6[]={0,0,0,0,0,0,0,0};
  modbus_write_bits(mb, 0, 8,mydata6);
  usleep(5);

  uint16_t  mydata3[8];
  cout<<modbus_read_registers(mb,0,8,mydata3)<<endl;
  cout<<"input data:"<<endl;
  cout<<(mydata3[0])<<"  "<<(mydata3[1])<<"  "<<(mydata3[2])<<"  "<<(mydata3[3])<<"  "<<(mydata3[4])<<"  "
  <<(mydata3[5])<<"  "<<(mydata3[6])<<"  "<<(mydata3[7])<<"  "<<endl;
  usleep(500000);


  /* Read 5 registers from the address 0 */
  // modbus_read_registers(mb, 4, 5, tab_reg);
  // cout<<tab_reg[0]<<"   "<<tab_reg[1]<<"   "<<tab_reg[2]<<"   "<<tab_reg[3]<<"   "<<tab_reg[4]<<"   "<<endl;
  // uint16_t  mydata[]={1,2,3,4,5,0,0,0};
  // modbus_write_registers(mb, 4, 8, mydata);

  for (int i = 0; i < 8; i++)
  {
    modbus_write_bit(mb, i, 1);
    usleep(500000);
    modbus_write_bit(mb, i, 0);
  }

    for (int i = 0; i < 8; i++)
  {
    modbus_write_bit(mb, i, 1);
    usleep(500000);
    // modbus_write_bit(mb, i, 0);
  }

  for (int i = 0; i < 4; i++)
  {
  uint8_t  mydata1[]={0,0,0,0,0,0,0,0};
  modbus_write_bits(mb, 0, 8,mydata1);
  usleep(500000);

  uint8_t  mydata2[]={1,1,1,1,1,1,1,1};
  modbus_write_bits(mb, 0, 8,mydata2);
  usleep(500000);
  }

    for (int i = 8; i > 0; i--)
  {
    modbus_write_bit(mb, i, 0);
    usleep(500000);
    // modbus_write_bit(mb, i, 0);
  }

  usleep(500000);
  modbus_close(mb);
  modbus_free(mb);
}